package com.nullpointer.xchatfinal;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageButton;

import com.edmodo.cropper.CropImageView;
import com.kbeanie.imagechooser.api.ChooserType;
import com.kbeanie.imagechooser.api.ChosenImage;
import com.kbeanie.imagechooser.api.ImageChooserListener;
import com.kbeanie.imagechooser.api.ImageChooserManager;
import com.nullpointer.xchatfinal.utils.ImageUtils;
import com.nullpointer.xchatfinal.utils.KiraGameLog;
import com.quickblox.content.model.QBFileObjectAccess;

public class ProcessImage extends Activity implements ImageChooserListener {
	// Layout
	private CropImageView civImage;
	private ImageButton ibRotateLeft;
	private ImageButton ibRotateRight;
	private Button btCrop;
	private ProgressDialog spinner;

	private ImageChooserManager imageChooserManager;
	private int chooserType;

	// Static final constants
	public static final String ASPECT_RATIO_X = "ASPECT_RATIO_X";
	public static final String ASPECT_RATIO_Y = "ASPECT_RATIO_Y";
	public static final String IS_CROP = "IS_CROP";
	public static final String IS_SELECT_IMAGE_FROM_CAMERA = "IS_SELECT_IMAGE_FROM_CAMERA";
	private static final String FOLDER_NAME = "XChat";
	// public static final String IMAGE_URL = "IMAGE_URL";
	public static final String LOCAL_URL = "LOCAL_URL";
	private static final int ON_TOUCH = 1;

	// Instance variables
	private int mAspectRatioX = 100;
	private int mAspectRatioY = 100;
	Bitmap croppedImage;
	private String filePath;

	QBFileObjectAccess fileObjectAccess;

	// Saves the state upon rotating the screen/restarting the activity
	@Override
	protected void onSaveInstanceState(Bundle bundle) {
		super.onSaveInstanceState(bundle);
		bundle.putInt(ASPECT_RATIO_X, mAspectRatioX);
		bundle.putInt(ASPECT_RATIO_Y, mAspectRatioY);
		bundle.putInt("chooser_type", chooserType);
		bundle.putString("media_path", filePath);
	}

	// Restores the state upon rotating the screen/restarting the activity
	@Override
	protected void onRestoreInstanceState(Bundle bundle) {
		super.onRestoreInstanceState(bundle);
		mAspectRatioX = bundle.getInt(ASPECT_RATIO_X);
		mAspectRatioY = bundle.getInt(ASPECT_RATIO_Y);
		chooserType = bundle.getInt("chooser_type");
		filePath = bundle.getString("media_path");
	}

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		// DataManager.getInstance(this).setIsShowNotify(false);
		setContentView(R.layout.activity_process_image);
		findViews();
		init();
		setEvent();
	}

	private void setEvent() {
		ibRotateRight.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				civImage.rotateImage(90);
			}
		});
		ibRotateLeft.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				civImage.rotateImage(-90);
			}
		});

		btCrop.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				croppedImage = civImage.getCroppedImage();
				new SaveImageTask().execute();
			}
		});
	}

	public void showProgessbar(String text) {
		spinner.setMessage(text);
		spinner.show();
	}

	public void hideProgessbar() {
		if (spinner == null) {
			return;
		}
		spinner.dismiss();
	}

	private void init() {
		spinner = new ProgressDialog(this);
		spinner.requestWindowFeature(Window.FEATURE_NO_TITLE);
		spinner.setCanceledOnTouchOutside(false);
		spinner.setCancelable(true);// avoid use click outside to
		spinner.setOnCancelListener(new OnCancelListener() {

			@Override
			public void onCancel(DialogInterface dialog) {
				finish();
			}
		});
		mAspectRatioX = getIntent().getIntExtra(ASPECT_RATIO_X, 100);
		mAspectRatioY = getIntent().getIntExtra(ASPECT_RATIO_Y, 100);
		boolean isCamera = getIntent().getBooleanExtra(
				IS_SELECT_IMAGE_FROM_CAMERA, false);
		// Initialize components of the app
		if (mAspectRatioX == 0 && mAspectRatioY == 0) {
			civImage.setFixedAspectRatio(false);
		} else {
			civImage.setFixedAspectRatio(true);
			// Sets initial aspect ratio to 10/10, for demonstration purposes
			civImage.setAspectRatio(mAspectRatioX, mAspectRatioY);
		}
		civImage.setGuidelines(ON_TOUCH);

		if (isCamera) {
			takePicture();
		} else {
			chooseImage();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		// getMenuInflater().inflate(R.menu.main, menu);
		return false;
	}

	private void findViews() {
		civImage = (CropImageView) findViewById(R.id.civ_image);
		ibRotateLeft = (ImageButton) findViewById(R.id.ib_rotate_left);
		ibRotateRight = (ImageButton) findViewById(R.id.ib_rotate_right);
		btCrop = (Button) findViewById(R.id.bt_crop);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK
				&& (requestCode == ChooserType.REQUEST_PICK_PICTURE || requestCode == ChooserType.REQUEST_CAPTURE_PICTURE)) {
			if (imageChooserManager == null) {
				reinitializeImageChooser();
			}
			imageChooserManager.submit(requestCode, data);
		} else {
			finish();
		}
	}

	private void takePicture() {
		showProgessbar("Loading...");
		chooserType = ChooserType.REQUEST_CAPTURE_PICTURE;
		imageChooserManager = new ImageChooserManager(this,
				ChooserType.REQUEST_CAPTURE_PICTURE, FOLDER_NAME, false);
		imageChooserManager.setImageChooserListener(this);
		try {
			filePath = imageChooserManager.choose();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
			finish();
		} catch (Exception e) {
			e.printStackTrace();
			finish();
		}
	}

	private void chooseImage() {
		showProgessbar("Loading...");
		chooserType = ChooserType.REQUEST_PICK_PICTURE;
		imageChooserManager = new ImageChooserManager(this,
				ChooserType.REQUEST_PICK_PICTURE, FOLDER_NAME, false);
		imageChooserManager.setImageChooserListener(this);
		try {
			filePath = imageChooserManager.choose();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
			finish();
		} catch (Exception e) {
			e.printStackTrace();
			finish();
		}
	}

	@Override
	public void onImageChosen(final ChosenImage image) {
		runOnUiThread(new Runnable() {

			@Override
			public void run() {
				if (image != null) {
					try {
						civImage.setImageBitmap(ImageUtils.resampleImage(
								image.getFilePathOriginal(), 640));
						File file = new File(image.getFilePathOriginal());
						if (file.exists()) {
							file.delete();
						}

						hideProgessbar();
					} catch (Exception e) {
						finish();
					}
				} else {
					finish();
				}
			}
		});
	}

	@Override
	public void onError(final String reason) {
		runOnUiThread(new Runnable() {

			@Override
			public void run() {
				hideProgessbar();
				finish();
				KiraGameLog.d("Choose image from gallery error " + reason);
			}
		});
	}

	// Should be called if for some reason the ImageChooserManager is null (Due
	// to destroying of activity for low memory situations)
	private void reinitializeImageChooser() {
		imageChooserManager = new ImageChooserManager(this, chooserType,
				FOLDER_NAME, true);
		imageChooserManager.setImageChooserListener(this);
		imageChooserManager.reinitialize(filePath);
	}

	private class SaveImageTask extends AsyncTask<Void, Void, String> {
		@Override
		protected void onPreExecute() {
			showProgessbar("uploading image...");
		}

		@Override
		protected String doInBackground(Void... params) {

			String root = Environment.getExternalStorageDirectory().toString();
			File newDir = new File(root + "/" + FOLDER_NAME);
			newDir.mkdir();
			String photoName = Long.toString(new Date().getTime()) + ".png";
			File file = new File(newDir, photoName);
			if (file.exists()) {
				file.delete();
			}
			FileOutputStream out;
			try {
				out = new FileOutputStream(file);
				KiraGameLog.d("image bitmap output2 "
						+ croppedImage.getByteCount());
				croppedImage.compress(Bitmap.CompressFormat.PNG, 100, out);
				KiraGameLog.d("image output2 " + file.length());
				out.flush();
				out.close();
				return file.getAbsolutePath();
			} catch (FileNotFoundException e) {
				e.printStackTrace();

			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			if (result != null) {
				KiraGameLog.d("Save image at " + result);
				finishAndCallBack(result);
			} else {
				KiraGameLog.d("Can not save this image!");
				finishAndCallBack(null);
			}
		}

	}

	public void finishAndCallBack(String localImage) {
		try {
			hideProgessbar();
		} catch (Exception e) {
			e.printStackTrace();
		}

		Intent returnIntent = new Intent();
		// returnIntent.putExtra(IMAGE_URL, urlImage);
		returnIntent.putExtra(LOCAL_URL, localImage);
		setResult(RESULT_OK, returnIntent);
		finish();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

}
